﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Sdari.Api.DbModel;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Sdari.Api.Gateway.Controllers
{
    [Authorize]
    public class ApiWhitelistController : Controller
    {
        private readonly ITokenServiceContext _db;
        private readonly ILogger<ApiWhitelistController> _logger;

        public ApiWhitelistController(ITokenServiceContext context, ILogger<ApiWhitelistController> logger)
        {
            _db = context;
            _logger = logger;
        }

        // GET: ApiWhitelists
        public async Task<IActionResult> Index()
        {
            var tokenDbConnection = _db.ApiWhitelist.Include(a => a.ApiU);
            return View(await tokenDbConnection.ToListAsync());
        }

        // GET: ApiWhitelists/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var apiWhitelist = await _db.ApiWhitelist
                .Include(a => a.ApiU)
                .FirstOrDefaultAsync(m => m.Id == id);
            if (apiWhitelist == null)
            {
                return NotFound();
            }

            return View(apiWhitelist);
        }

        // GET: ApiWhitelists/Create
        public IActionResult Create()
        {
            ViewData["ApiUid"] = new SelectList(_db.ApiInfo, "Uid", "Address");
            return View();
        }

        // POST: ApiWhitelists/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Uid,Id,ApiUid,Value,Type,IsValid,Creator,CreateDate,LastUpdater,LastUpdatedDate")] ApiWhitelist apiWhitelist)
        {
            if (ModelState.IsValid)
            {
                apiWhitelist.Uid = Guid.NewGuid();
                apiWhitelist.CreateDate = DateTime.Now;
                apiWhitelist.Creator = User.FindFirst("work_no")?.Value;
                _db.Add(apiWhitelist);
                await _db.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            ViewData["ApiUid"] = new SelectList(_db.ApiInfo, "Uid", "Address", apiWhitelist.ApiUid);
            return View(apiWhitelist);
        }

        // GET: ApiWhitelists/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var apiWhitelist = await _db.ApiWhitelist.FindAsync(id);
            if (apiWhitelist == null)
            {
                return NotFound();
            }
            ViewData["ApiUid"] = new SelectList(_db.ApiInfo, "Uid", "Address", apiWhitelist.ApiUid);
            return View(apiWhitelist);
        }

        // POST: ApiWhitelists/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Uid,Id,ApiUid,Value,Type,IsValid")] ApiWhitelist apiWhitelist)
        {
            if (id != apiWhitelist.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _db.Attach(apiWhitelist);
                    var en = _db.Entry(apiWhitelist);
                    en.Property(nameof(apiWhitelist.ApiUid)).IsModified = true;
                    en.Property(nameof(apiWhitelist.Value)).IsModified = true;
                    en.Property(nameof(apiWhitelist.Type)).IsModified = true;
                    en.Property(nameof(apiWhitelist.IsValid)).IsModified = true;
                    apiWhitelist.LastUpdatedDate = DateTime.Now;
                    apiWhitelist.LastUpdater = User.FindFirst("work_no")?.Value;
                    //_context.Update(apiWhitelist);
                    await _db.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ApiWhitelistExists(apiWhitelist.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            ViewData["ApiUid"] = new SelectList(_db.ApiInfo, "Uid", "Address", apiWhitelist.ApiUid);
            return View(apiWhitelist);
        }

        // GET: ApiWhitelists/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var apiWhitelist = await _db.ApiWhitelist
                .Include(a => a.ApiU)
                .FirstOrDefaultAsync(m => m.Id == id);
            if (apiWhitelist == null)
            {
                return NotFound();
            }

            return View(apiWhitelist);
        }

        // POST: ApiWhitelists/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var apiWhitelist = await _db.ApiWhitelist.FindAsync(id);
            _db.ApiWhitelist.Remove(apiWhitelist);
            await _db.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool ApiWhitelistExists(int id)
        {
            return _db.ApiWhitelist.Any(e => e.Id == id);
        }
    }
}
